<template>
    <div class="xm-list-page" ref="listPageRef">
        <van-list
            v-model="loading"
            :finished="this.current >= this.pageTotal"
            finished-text="没有更多了"
            @load="onLoad"
        >
            <van-cell v-for="item in list" :key="item.id">
                <XmItem :item="item" @toDetail="toDetail($event)" />
            </van-cell>
        </van-list>
    </div>
</template>

<script>
import XmItem from '@/components/XmItem.vue'
import HttpTools from '@/utils/http'
export default {
  name: 'XmListPage',
  components: {
    XmItem
  },
  props: {
    url: String,
    query: {
      type: Object,
      default: () => {}
    }
  },
  data () {
    return {
      flag: false,
      loading: false,
      current: 1,
      pageTotal: -1,
      total: -1,
      list: [],
      scrollTop: 0
    }
  },
  watch: {
    // 监听query的变化
    query () {
      this.getList()
    }
  },
  created () {
    this.getList()
  },
  methods: {
    async getList () {
      if (!this.url || this.flag) {
        return
      }
      this.flag = true
      const { data } = await HttpTools.get(this.url, this.query)

      if (data?.current > this.current) {
        this.list.push(...(data?.rows || []))
      } else {
        this.list = data?.rows || []
      }
      this.current = data?.current
      this.pageTotal = data?.pageTotal
      this.total = data?.total
      this.loading = false
      this.flag = false
    },
    onLoad () {
      if (this.current < this.pageTotal) {
        this.$emit('onLoad')
      }
    },
    toDetail (id) {
      this.scrollTop = this.$refs.listPageRef.scrollTop
      this.$router.push({
        path: '/details',
        query: {
          id
        }
      })
    }
  },
  activated () {
    this.$refs.listPageRef.scrollTop = this.scrollTop
  }
}
</script>
<style lang="less" scoped>
.xm-list-page {
    // height: 100%;
    // overflow: auto;
}
</style>
